package com.hugang.juc.assistclass;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量——抢车位
 *
 * @author hg
 * @date 2020/8/20 16:29
 */
public class SemaphoreDemo {

    public static void main(String[] args) {

        //3个车位
        Semaphore semaphore = new Semaphore(1);
        //6个线程抢车位
        for (int i = 1; i <= 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() +" ---> " + "抢到了车位");
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName() +" ---> " + "离开了车位");
                    semaphore.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();

        }
    }
}
